/* api */
import { creatServerCachApi, getUserGuideStorageFor } from '@src/api/GuideApi';
/* vue */
import { defineComponent, ref, computed, inject } from 'vue'
/* scss */
import '@src/modules/im/imChat/components/messageBox/AutoAIReplySwitch/index.scss'
/* model */
import MsgModel from '@model/MsgModel';
/* util */
import { parse, parse_with_default_value } from '@src/util/lang/object';
import _ from 'lodash';

enum AutoAIReplySwitchEventEnum {
  Change = 'change'
}

export default defineComponent({
  name: 'AutoAIReplySwitch',
  props: {
    conversationId: {
      type: [String, Number],
    },
    imConfig: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      storageKey: 'AutoAIReplySwitch',
      value: false
    }
  },
  computed: {
    contentTooltipText() {
      return 'AI主动介入'
    },
    contentText() {
      return 'AI主动介入'
    }
  },
  mounted() {
    this.getValueFromServer()
  },
  methods: {
    debounceOnChangeHandler: _.debounce(function(value: boolean) {
      // @ts-ignore
      this.onChangeHandler(value)
    }, 300),
    onChangeHandler(value: boolean) {
      this.onChangeHandlerImpl(value)
      this.saveValueToServer()
    },
    onChangeHandlerImpl(value: boolean) {
      this.value = value
      this.$emit(AutoAIReplySwitchEventEnum.Change, value)
    },
    saveValueToServer() {
      creatServerCachApi({
        isComplete: 1, 
        step: 1,
        type: this.storageKey,
        userConfig: JSON.stringify({
          value: this.value,
          conversationId: this.conversationId
        })
      })
    },
    async getValueFromServer() {
      
      const result = await getUserGuideStorageFor({ 
        type: this.storageKey 
      })
      
      const isFail = MsgModel.isFail(result)
      if (isFail) {
        return
      }

      const data = MsgModel.getData(result) as Record<string, any>
      const userConfig = data?.userConfig || ''
      const config = parse_with_default_value(userConfig, {}) as Record<string, any>
      
      const value = Boolean(config?.value)
      
      this.onChangeHandlerImpl(value)
    }
  },
  render() {
    return (
      <div class="auto-ai-reply-switch">
        <el-tooltip
          effect="dark" 
          placement="top" 
          content={this.contentTooltipText}
        >
          <el-switch 
            disabled={this.disabled}
            value={this.value}
            activeText={this.contentText}
            onChange={this.debounceOnChangeHandler}
          >
            {this.contentText}
          </el-switch>
        </el-tooltip>
      </div>
    );
  }
})
